package com.june.junemplayer.controller;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelStoreOwner;

import com.june.junemplayer.mapper.SongListContentMapper;
import com.june.junemplayer.mapper.SongListMapper;
import com.june.junemplayer.mapper.SongMapper;
import com.june.junemplayer.pojo.Song;
import com.june.junemplayer.pojo.SongList;
import com.june.junemplayer.receiver.InitReceiver;
import com.june.junemplayer.utils.DataConversionUtil;
import com.june.junemplayer.view.LocalSongListActivity;
import com.june.junemplayer.viewModel.GlobalViewModel;

import java.util.ArrayList;
import java.util.Map;

public class GlobalViewModelController {

    private SongMapper mSongMapper;
    private SongListMapper mSongListMapper;
    private SongListContentMapper mSongListContentMapper;

    private GlobalViewModel mGlobalViewModel;

    private static int[] mPlayingListPosition;


    public GlobalViewModelController(ViewModelStoreOwner application) {
        Log.d("JuneGlVMCtl", "----Constructor----start----");
        mGlobalViewModel = new ViewModelProvider(application).get(GlobalViewModel.class);
        mSongMapper = new SongMapper();
        mSongListMapper = new SongListMapper();
        mSongListContentMapper = new SongListContentMapper();
        Log.d("JuneGlVMCtl", "----Constructor----end----");
    }

    public ArrayList<Song> getSongs() {
        return mGlobalViewModel.getSongs();
    }

    public ArrayList<SongList> getCustomSongList() {
        return mGlobalViewModel.getCustomSongList();
    }

    public Map<String, SongList> getDefaultSongListMap() {
        return mGlobalViewModel.getDefaultSongListMap();
    }

    public SongList getLoveSongList() {
        return mGlobalViewModel.getDefaultSongListMap().get(SongList.LOVE);
    }

    public SongList getRecentSongList() {
        return mGlobalViewModel.getDefaultSongListMap().get(SongList.RECENT);
    }

    public ArrayList<Song> getPlayingList() {
        return mGlobalViewModel.getPlayingList();
    }

    public void addToPlayingList(Song song) {
        Log.d("JuneGlVMCtl", "----addToPlayingList() start:song = " + song + "----");
        Log.d("JuneGlVMCtlInfo", "start----" + getInfo());
        mPlayingListPosition[1]++;
        mGlobalViewModel.getPlayingList().add(song);
        Log.d("JuneGlVMCtlInfo", "end----" + getInfo());
        Log.d("JuneGlVMCtl", "----addToPlayingList end----");
    }

    public void addToPlayingList(int position, Song song) {
        Log.d("JuneGlVMCtl", "----addToPlayingList() start:position = " + position + ",song = " + song + "----");
        Log.d("JuneGlVMCtlInfo", "start----" + getInfo());
        if (mGlobalViewModel.getPlayingList().contains(song)) {
            mGlobalViewModel.getPlayingList().remove(song);
            mGlobalViewModel.getPlayingList().add(0, song);
            mPlayingListPosition[0] = 0;
            return;
        } else if (position == 0) {
            mPlayingListPosition[0] = 0;
        }
        mPlayingListPosition[1]++;
        mGlobalViewModel.getPlayingList().add(position, song);
        Log.d("JuneGlVMCtlInfo", "end----" + getInfo());
        Log.d("JuneGlVMCtl", "----addToPlayingList end----");
    }

    public Song removeFromPlayingList(int position) {
        Log.d("JuneGlVMCtl", "----removeFromPlayingList() start:position = " + position + "----");
        Log.d("JuneGlVMCtlInfo", "start----" + getInfo());
        mPlayingListPosition[1]--;
        if (mPlayingListPosition[0] <= position) {
            mPlayingListPosition[0]--;
        }
        Song song = mGlobalViewModel.getPlayingList().remove(position);
        Log.d("JuneGlVMCtlInfo", "end----" + getInfo());
        Log.d("JuneGlVMCtl", "----removeFromPlayingList() end:removeSong = " + song + "----");
        return song;
    }

    public Song getNextInPlayingList() {
        Log.d("JuneGlVMCtl", "----getNextInPlayingList() start----");
        Log.d("JuneGlVMCtlInfo", "start----" + getInfo());
        if (mPlayingListPosition[0] == mPlayingListPosition[1]) {
            mPlayingListPosition[0] = 0;
        } else {
            mPlayingListPosition[0]++;
        }
        Song song = mGlobalViewModel.getPlayingList().get(mPlayingListPosition[0]);
        Log.d("JuneGlVMCtlInfo", "end----" + getInfo());
        Log.d("JuneGlVMCtl", "----getNextInPlayingList() end:nextSong = " + song + "----");
        return song;
    }

    public Song getForeInPlayingList() {
        Log.d("JuneGlVMCtl", "----getForeInPlayingList() start----");
        Log.d("JuneGlVMCtlInfo", "start----" + getInfo());
        if (mPlayingListPosition[0] == 0) {
            mPlayingListPosition[0] = mPlayingListPosition[1];
        } else {
            mPlayingListPosition[0]--;
        }
        Song song = mGlobalViewModel.getPlayingList().get(mPlayingListPosition[0]);
        Log.d("JuneGlVMCtlInfo", "end----" + getInfo());
        Log.d("JuneGlVMCtl", "----getForeInPlayingList() end:foreSong = " + song + "----");
        return song;
    }

    public Song getPlayingSong() {
        if (mPlayingListPosition[0] == -1) {
            return null;
        }
        return mGlobalViewModel.getPlayingList().get(mPlayingListPosition[0]);
    }

    public ArrayList<Song> getLoveSongs(Context context) {
        Log.d("JuneGlVMCtl", "----getLoveSongs() start----");
        ArrayList<String> songTitles = mSongListContentMapper.retrieveSongsBySongListTitle(context, SongList.LOVE);
        ArrayList<Song> mSongs=mGlobalViewModel.getSongs();
        Map<String, Song> mSongsMap=mGlobalViewModel.getSongsMap();
        ArrayList<Song> songs = new ArrayList<>();
        if (songTitles.size() == 0) {
            return songs;
        }
        for (String title : songTitles) {
            Song song=mSongsMap.get(title);
            //首先判断该歌曲是否存在
            if(song==null){
                song=new Song();
                song.setTitle(title);
            }
            songs.add(song);
        }
        return songs;
    }

//    public ArrayList<Song> getSongInSongList(long listId) {
//        if (mGlobalViewModel.isSongListContentsEmpty(listId)) {
//            return new ArrayList<>();
//        }
//        ArrayList<Long> longs = mGlobalViewModel.getSongListContents(listId);
//        Map<Long, Song> songStore = mGlobalViewModel.getSongs();
//        ArrayList<Song> songs = new ArrayList<>();
//        for (Long aLong : longs) {
//            songs.add(songStore.get(aLong));
//        }
//        return songs;
//    }

    public void init(Context context) {
        Log.d("JuneGlVMCtl", "----init() start----");
        ArrayList<Song> songs = mSongMapper.retrieveAllSongs(context);
        ArrayList<SongList> songLists = mSongListMapper.retrieveAllSongLists(context);
        ArrayList<SongList> defaultList = new ArrayList<>();
        if (songs.size() == 0) {
            Log.d("JuneGlVMCtl", "!!!NOTICE!!!----this is 0 song----");
        }
        if (songLists.size() == 0) {
            SongList songList1 = new SongList();
            songList1.setTitle(SongList.RECENT);
            songList1.setNumber(0);
            songList1.setCover("default");
            defaultList.add(songList1);
            SongList songList2 = new SongList();
            songList2.setTitle(SongList.LOVE);
            songList2.setNumber(0);
            songList2.setCover("default");
            defaultList.add(songList2);
            mSongListMapper.insert(context, songList1);
            mSongListMapper.insert(context, songList2);
        } else {
            for (SongList songList : songLists) {
                if (songList.getTitle().equals(SongList.LOVE) || songList.getTitle().equals(SongList.RECENT)) {
                    defaultList.add(songList);
                }
            }
            /**
             * 不能在循环里remove，原因是循环是list的迭代循环会调用hasNext
             * hasNext有个checkForComodification方法，这个方法会进行检测
             * 检测如果校验修改的条数如果不等于被期待的修改数量，则报错
             */
            songLists.removeAll(defaultList);
        }
        mPlayingListPosition = new int[2];
        mPlayingListPosition[0] = -1;
        mPlayingListPosition[1] = -1;
        mGlobalViewModel.init(songs, songLists, defaultList);

        InitReceiver initReceiver = new InitReceiver();
        IntentFilter itFilter = new IntentFilter();
        itFilter.addAction(InitReceiver.DATA_INIT);
        context.registerReceiver(initReceiver, itFilter);
        context.sendBroadcast(new Intent(InitReceiver.DATA_INIT));

        Log.d("JuneGlVMCtl", "end----" + getInfo());
        Log.d("JuneGlVMCtl", "----init() end----");
    }

    public int getSongsFromProvider(Context context) {
        Log.d("JuneGlVMCtl", "----getSongsFromProvider() start----");
        ArrayList<Song> songs = new ArrayList<>();
        Map<String, Song> songsMap = mGlobalViewModel.getSongsMap();
        songs = DataConversionUtil.getSongsFromProvider(context);
        //将已有的歌曲移除
        songs.removeIf(song -> songsMap.containsKey(song.getPath()));
        Log.d("JuneGlVMCtlInfo", "----去重后新扫描到歌曲  " + songs.size() + "  首----");
        if (songs.size() != 0) {
            for (Song song : songs) {
                mSongMapper.insert(context, song);
                mGlobalViewModel.addSong(song);
            }
            //service将歌曲添加到数据库
        }
        Log.d("JuneGlVMCtl", "----getSongsFromProvider() end----");
        return songs.size();
    }

    private String getInfo() {
        return "mPlayingListPosition = [" + mPlayingListPosition[0] + "][" + mPlayingListPosition[1] + "]";
    }


}
